﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Castle.Windsor;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel;
using Castle.Core;
using Castle.MicroKernel.Context;

namespace WindsorInitConfig
{
    [TestFixture]
    public class TypeArgConstraint
    {
        public class Entity { }
        public interface IDel { }
        public class DelEntity : Entity, IDel { }

        public interface IRepo<T> { }

        public class EntRepo<T> : IRepo<T> where T : Entity { }

        public class DelRepo<T> : IRepo<T> where T : Entity, IDel {}

        public class RepoHandlerSelector : IHandlerSelector {

            public bool HasOpinionAbout(string key, Type service) {
                throw new NotImplementedException();
            }

            public IHandler SelectHandler(string key, Type service, IHandler[] handlers) {
                throw new NotImplementedException();
            }
        }


        [Test]
        public void Resolve()
        {
            var c = new WindsorContainer();
            c.Register(Component.For(typeof(IRepo<>)).UsingFactoryMethod<IRepo<Entity>>((kernel, model, ctx) => {
                IHandler h;
                if (typeof(IDel).IsAssignableFrom(ctx.GenericArguments[0]))
                    h = kernel.GetHandler("delRepo");
                h = kernel.GetHandler("entRepo");
                return (IRepo<Entity>)h.Resolve(ctx);
            }));
            c.Register(Component.For(typeof(IRepo<>)).ImplementedBy(typeof(EntRepo<>)).Named("entRepo"));
            c.Register(Component.For(typeof(IRepo<>)).ImplementedBy(typeof(DelRepo<>)).Named("delRepo"));

            Assert.IsInstanceOf<EntRepo<Entity>>(c.Resolve<IRepo<Entity>>());
            Assert.IsInstanceOf<DelRepo<DelEntity>>(c.Resolve<IRepo<DelEntity>>());
        }
    }
}
